<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入文件：和view同目录选择 -->
    <link rel="stylesheet" href="../public/layui/css/layui.css">
    <script src="../public/layui/layui.js"></script>
    <script src="../public/jquery.min.js"></script>
    <link rel="stylesheet" href="../public/editor.md-master/css/editormd.min.css">
    <script src="../public/editor.md-master/editormd.js"></script>
    <link rel="stylesheet" href="../public/base.css">
    <link rel="stylesheet" href="../public/icon/iconfont.css">
</head>

<body>
    <div class="files">
        <div class="title">
            <h1>资源管理</h1>
            <button type="button" kb-event="tool" class="layui-btn layui-btn-xs layui-btn-primary layui-border">
                <i class="layui-icon layui-icon-more-vertical"></i>
            </button>
        </div>
        <div class="tree-box">
            <ul class="layui-menu" lay-filter="menu">
            </ul>
        </div>
    </div>
    <div class="editor">
    </div>
</body>
<script type="text/javascript">
    layui.use(function () {
        let dropdown = layui.dropdown;
        let layer = layui.layer;
        let editor_arr = [];
        let editor_config = {
            width: "100%",
            height: "100%",
            path: "../public/editor.md-master/lib/",
            toolbarIcons: function () {
                return [
                    "undo", "redo", "|",
                    "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
                    "h1", "h2", "h3", "h4", "h5", "h6", "|",
                    "list-ul", "list-ol", "hr", "|",
                    "link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "pagebreak", "|",
                    "goto-line", "watch", "preview", "clear", "search", "|", "info"
                ]
            },
            saveHTMLToTextarea: true,
            onchange: function () {
                let file = $(`#${this.id}`).attr("data-id");
                let content = this.getMarkdown();
                updateFile(file, content)
            }
        };

        // 树形结构
        function treeRender(arr) {
            let html = "";
            arr.forEach(function (v, k) {
                let class_name = "";
                let i = `<i class="layui-icon layui-icon-file"></i>`;
                let i2 = "";
                let children = "";
                if (!v.is_file) {
                    class_name = `class="layui-menu-item-group layui-menu-item-down"`
                    i = `<i class="iconfont icon-sucai"></i>`;
                    i2 = `<i class="layui-icon layui-icon-up"></i>`
                }
                children = "<ul>" + treeRender(v.children) + "</ul>"
                html += `<li ${class_name} data-id="${v.id}" lay-options='{"id":"${v.id}","title":"${v.title}","is_file":${v.is_file},"key":"${v.key}"}'>
                        <div class="layui-menu-body-title">
                            <span>${i}${v.title}</span>
                            ${i2}
                        </div>
                        ${children}
                    </li>`;
            })
            return html;
        }

        // 获取文件后缀名
        function getFileExtension(filename) {
            return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
        }

        // 禁止右键
        $("body").on("contextmenu", function (e) {
            e.preventDefault();
        })

        // 右键文件
        $("body").delegate(".layui-menu li .layui-menu-body-title", "contextmenu", function (e) {
            let then = $(this).parent();
            e.preventDefault();
            let options = JSON.parse($(then).attr("lay-options").replace(/\\/g, "\\/"))
            let data = [
                { "title": "重命名", "id": "rename" },
                { "title": "删除", "id": "delete" }
            ]
            if (!options.is_file) {
                data.unshift(
                    { "title": "新建文件", "id": "new_file" },
                    { "title": "新建文件夹", "id": "new_folder" }
                )
            }
            // 右键菜单
            dropdown.render({
                elem: then, // 也可绑定到 document，从而重置整个右键
                trigger: 'contextmenu', // contextmenu
                show: true,
                data: data,
                click: function (obj, othis) {
                    switch (obj.id) {
                        case "new_file":
                            openCustom({
                                title: "新建文件",
                                type: "file",
                                url: options.id
                            })
                            break;
                        case "new_folder":
                            openCustom({
                                title: "新建文件夹",
                                type: "folder",
                                url: options.id
                            })
                            break;
                        case "rename":
                            openCustom({
                                title: "重命名",
                                type: "rename",
                                url: options.id
                            })
                            break;
                        case "delete":
                            let confirm = layer.confirm('确定删除吗？', {
                                icon: 3,
                                btn: ['确定', '关闭'] //按钮
                            }, function () {
                                deleteFile(options.id).then(function (res) {
                                    if (res["code"] == 0) {
                                        $(`li[data-id="${options.id}"]`).remove()
                                        if ($(".layui-menu li".length == 0)) {
                                            editor_arr.forEach(function (v, k) {
                                                v.editor.remove();
                                            })
                                        }
                                        layer.close(confirm);
                                    } else {
                                        layer.msg(res["msg"], { icon: 2 });
                                    }
                                })
                            });
                            break;
                    }
                }
            });
        })

        querys()

        // 点击工具
        $('[kb-event="tool"]').on("click", function () {
            let then = this;
            dropdown.render({
                elem: then,
                show: true,
                data: [{
                    title: '新增文件(Ctrl + O)',
                    id: 1
                }, {
                    title: '新增文件夹(Ctrl + N)',
                    id: 2
                }, {
                    title: '刷新(Ctrl + R)',
                    id: 3
                }, {
                    title: '打开目录(Ctrl + X)',
                    id: 4
                }],
                click: function (obj) {
                    switch (obj.id) {
                        case 1:
                            openCustom({
                                title: "新建文件",
                                type: "file",
                            })
                            break;
                        case 2:
                            openCustom({
                                title: "新建文件夹",
                                type: "folder",
                            })
                            break;
                        case 3:
                            window.location.reload()
                            break;
                        case 4:
                            opens()
                            break;
                    }
                }
            });
        })

        // 监听键盘事件
        document.addEventListener("keydown", function (event) {
            if (event.ctrlKey && event.key === "o") {
                openCustom({
                    title: "新建文件",
                    type: "file",
                })
            } else if (event.ctrlKey && event.key === "n") {
                openCustom({
                    title: "新建文件夹",
                    type: "folder",
                })
            } else if (event.ctrlKey && event.key === "x") {
                opens()
            }
        });

        // 查询
        function querys(callback = () => { }) {
            query().then(function (res) {
                if (res["code"] == 0) {
                    let arr = res["data"];
                    let html = treeRender(arr)
                    $(".tree-box .layui-menu").html(html)
                    callback()
                } else {
                    layer.msg(res["msg"]);
                }
            })
        }

        // 点击文件事件
        $("body").delegate(".layui-menu li", "click", function () {
            let obj = JSON.parse($(this).attr("lay-options").replace(/\\/g, "\\/"))
            if (obj.is_file) {
                let editor = $(`.editor #editor-${obj.key}`)
                if (editor.length == 0) {
                    let load = layer.load(1);
                    $(".editor").append(`<div class="editor-box" id="editor-${obj.key}" data-id="${obj.id}"></div>`)
                    getFileContent(obj.id).then(function (res) {
                        if (res["code"] == 0) {
                            editor_config.markdown = res["data"];
                            editor_arr[obj.key] = editormd(`editor-${obj.key}`, editor_config);
                        } else {
                            layer.msg(res["msg"], { icon: 2 });
                        }
                        layer.close(load);
                    })
                }
                $(".editor .editor-box").hide()
                $(`.editor #editor-${obj.key}`).show()
            }
        })

        // 弹出询问
        function openCustom(options) {
            options.title = options.title || "提示";
            options.type = options.type || "file";
            options.url = options.url || "";

            let open_demo = layer.open({
                type: 1,
                area: '300px',
                resize: false,
                shadeClose: true,
                title: options.title,
                content: `<form class="layui-form layui-form-pane" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">名称</label>
                    <div class="layui-input-block">
                    <input type="text" name="name" autocomplete="off" required lay-verify="required" placeholder="请输入名称" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item" style="margin-bottom:5px;text-align:right;padding-right:10px">
                    <button class="layui-btn" lay-submit lay-filter="demo2">确认</button>
                </div>
                </form>`,
                success: function (layero, index) {
                    layui.form.on('submit(demo2)', function (data) {
                        var field = data.field; // 获取表单字段值
                        if (options.type !== "rename") {
                            create(field.name, options.type, options.url).then(function (res) {
                                if (res["code"] == 0) {
                                    querys(function () {
                                        $(`.layui-menu li[data-id="${res["data"]}"]`).click()
                                        layer.close(open_demo)
                                    })
                                } else {
                                    layer.msg(res["msg"], { icon: 2 });
                                }
                            })
                        } else {
                            renames(options.url, field.name).then(function (res) {
                                if (res["code"] == 0) {
                                    querys(function () {
                                        $(`.layui-menu li[data-id="${res["data"]}"]`).click()
                                        layer.close(open_demo)
                                    })
                                } else {
                                    layer.msg(res["msg"], { icon: 2 });
                                }
                            })
                        }
                        return false; // 阻止默认 form 跳转
                    });
                }
            })
        }

    })
</script>

</html>